﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using ExcellentCRM.DataService.IServices;
using ExcellentCRM.DataService.Models;

namespace ExcellentCRM.DataService.Implements
{
    public class BaseService<T> : IBaseService<T> where T : BaseModel
    {
        public virtual T GetModel(long id)
        {
            using (var dbCtx = new DataServiceContext())
            {
                return dbCtx.Set<T>().FirstOrDefault(p => p.Id == id);
            }
        }

        public virtual IEnumerable<T> GetModels()
        {
            using (var dbCtx = new DataServiceContext())
            {
                return dbCtx.Set<T>().Where(p => p.StatusToken != 0).ToList();
            }
        }

        public virtual ServiceResult Delete(long id)
        {
            using (var dbCtx = new DataServiceContext())
            {
                var entry = dbCtx.Set<T>().FirstOrDefault(p => p.Id == id);
                if (entry != null)
                {
                    entry.StatusToken = 0;
                    entry.LastModifiedTime = DateTime.Now;
                    dbCtx.Entry(entry).State = EntityState.Modified;
                    int savedRowNum = dbCtx.SaveChanges();
                    return savedRowNum > 0
                               ? ServiceResult.SuccessResult
                               : new ServiceResult(false, "删除失败");
                }
                return ServiceResult.SuccessResult;
            }
        }

        public virtual ServiceResult Save(T model)
        {
            using (var dbCtx = new DataServiceContext())
            {
                if (model.Id <= 0)
                {
                    dbCtx.Set<T>().Add(model);
                }
                else
                {
                    model.LastModifiedTime = DateTime.Now;
                    dbCtx.Entry(model).State = EntityState.Modified;
                }
                int savedRowNum = dbCtx.SaveChanges();
                return savedRowNum > 0
                               ? ServiceResult.SuccessResult
                               : new ServiceResult(false, "保存失败");
            }
        }
    }
}